package twice.class02;

//i < j 且 nums[i] > 2*nums[j] 个数
//leetcode 493
public class ReversePairsTwoBig {
    public static int reversePairs(int[] arr){
        if(arr == null || arr.length < 2){
            return 0;
        }
        return process(arr,0,arr.length-1);
    }
    static int process(int[] arr,int L,int R){
        if(L == R){return 0;}
        int M = L + (R - L)/2;
        return process(arr,L,M) + process(arr,M + 1,R) + merge(arr,L,M,R);
    }
    static int merge(int[] arr,int L,int M,int R){
        int ans = 0;
        int window = M + 1;//[M+1,window)
        for(int i = L;i <= M;i++){
            while(window <= R && arr[i] > (long) arr[window] * 2){
                window++;
            }
            ans += window - (M + 1);
        }
        int[] help = new int[R - L + 1];

        int p1 = L;
        int p2 = M + 1;
        int i = 0;
        while(p1 <= M && p2 <= R){

            help[i++] = arr[p1] < arr[p2] ? arr[p1++] : arr[p2++];
        }
        while (p1 <= M) {
            help[i++] = arr[p1++];
        }
        while (p2 <= R) {
            help[i++] = arr[p2++];
        }
        for (i = 0; i < help.length; i++) {
            arr[L + i] = help[i];
        }
        return ans;
    }
}
